package com.xiekong.rpc.handler;

import com.xiekong.rpc.bean.RpcRequest;
import com.xiekong.rpc.bean.RpcResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author XieKong
 */
public class RpcFuture {
    private static final Logger logger = LoggerFactory.getLogger(RpcFuture.class);
    private final static ConcurrentHashMap<String, RpcFuture> allRpcFuture = new ConcurrentHashMap<String, RpcFuture>();
    final Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    private RpcResponse response;

    public RpcFuture(RpcRequest request) {
        allRpcFuture.put(request.getRequestId(), this);
    }

    public RpcResponse getResponseResult() {
        lock.lock();
        try {
            if (!done()) {
                condition.await();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("", e);
        } finally {
            lock.unlock();
        }
        return this.response;
    }

    public static void setResponseResult(RpcResponse response) {
        RpcFuture future = allRpcFuture.get(response.getRequestId());
        if (future != null) {
            Lock lock = future.lock;
            lock.lock();
            try {
                future.setResponse(response);
                future.condition.signal();
            } finally {
                lock.unlock();
            }
        }
    }

    public void setResponse(RpcResponse response) {
        this.response = response;
    }

    public boolean done() {
        if (this.response == null) {
            return false;
        }
        return true;
    }
}
